package com.puman.beautyfarmcounselor.ui.customer;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.beautyfarmcounselor.IndexActivity;
import com.puman.beautyfarmcounselor.MainActivity;
import com.puman.beautyfarmcounselor.R;
import com.puman.beautyfarmcounselor.http.AjaxCallBack;
import com.puman.beautyfarmcounselor.ui.core.BaseFragment;
import com.puman.beautyfarmcounselor.ui.core.BaseInferface;
import com.puman.beautyfarmcounselor.ui.customer.adpter.LableGridviewAdapter;
import com.puman.beautyfarmcounselor.ui.customer.model.LableData;
import com.puman.beautyfarmcounselor.ui.customer.model.LableInfo;
import com.puman.beautyfarmcounselor.util.MethedUtil;
import com.puman.beautyfarmcounselor.util.PublicData;
import com.puman.beautyfarmcounselor.util.XTHttp;
import com.puman.beautyfarmcounselor.util.config.GlobalData;
import com.puman.beautyfarmcounselor.util.config.RequestAddr;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ItemLongClick;
import org.androidannotations.annotations.ViewById;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 */
@EFragment(R.layout.fragment_cus_lable)
public class CusLableFragment extends BaseFragment implements BaseInferface {

    @ViewById(R.id.edit_layout)
    LinearLayout editLayout;
    @ViewById(R.id.lable_edit)
    EditText editLable;

    public int textWidth = 0;

    CusLableFragment cusLableFragment;

    public List<LableInfo> cusLableList = new ArrayList<>();
    public List<LableInfo> libLableList = new ArrayList<>();
    public LableGridviewAdapter cusAdapter;
    public LableGridviewAdapter libAdapter;

    @ViewById(R.id.lable_customer_grideview)
    GridView cusGridView;

    @ViewById(R.id.lable_grideview)
    GridView libGridView;
    @FragmentArg
    String lableList;
    @FragmentArg
            int customer_id;

    String[] lables;

    @Override
    @AfterViews
    public void updateView() {
        cusLableFragment = this;

        lables = lableList.split(",");
        for (int i = 0; i < lables.length; i++) {
            LableInfo lableInfo = new LableInfo();
            lableInfo.setName(lables[i]);
            lableInfo.setIsSelect(false);
            cusLableList.add(lableInfo);
        }
        getData();
        RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) editLayout.getLayoutParams();//获取控件的当前布局
        textWidth = linearParams.width;
        editLable.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                if (s.length() == 0) {
                    RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) editLayout.getLayoutParams();//获取控件的当前布局
                    linearParams.width = textWidth;//对该控件的布局参数做修改
                    editLayout.setLayoutParams(linearParams);//重新设定布局
                } else {
                    if (s.length() > 4) {
                        Toast.makeText(MainActivity.getInstace(), "标签最多不要超过4个字符哦", Toast.LENGTH_SHORT).show();
                        editLable.setText(editLable.getText().toString().subSequence(0, 4));
                        return;
                    }
                    RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) editLayout.getLayoutParams();//获取控件的当前布局
                    linearParams.width = android.widget.LinearLayout.LayoutParams.WRAP_CONTENT;//对该控件的布局参数做修改
                    editLayout.setLayoutParams(linearParams);//重新设定布局
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
        editLable.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				Log.i("curry", "onclick");
                RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) editLayout.getLayoutParams();//获取控件的当前布局
                linearParams.width = textWidth;//对该控件的布局参数做修改
                editLayout.setLayoutParams(linearParams);//重新设定布局
            }
        });
        editLable.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                // TODO Auto-generated method stub
                /* 判断是否是“GO”键 */
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    /* 隐藏软键盘 */

                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    // editLable.setText("success");
                    if (editLable.getText().toString().equals("")) {
//                        Toast.makeText(MainActivity.getInstace(), "不能为空哦",
//                                Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    if (v.getText().length() > 4) {
                        Toast.makeText(MainActivity.getInstace(), "标签最多不要超过4个字符哦", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    for (int i = 0; i < libLableList.size(); i++) {
                        if (libLableList.get(i).equals(editLable.getText().toString().trim()))
                            return true;

                    }
                    LableInfo lableInfo = new LableInfo();
                    lableInfo.setName(editLable.getText().toString());
                    lableInfo.setIsSelect(false);
                    cusLableList.add(lableInfo);
                    addTag(lableInfo.getName());
                    modifyLayout();
                    editLable.setText("");
                    cusAdapter.notifyDataSetChanged();
                    libAdapter.notifyDataSetChanged();
                    return true;
                }
                return false;
            }
        });


        cusAdapter = new LableGridviewAdapter(cusLableFragment, 1);
        cusGridView.setAdapter(cusAdapter);
        libAdapter = new LableGridviewAdapter(cusLableFragment, 2);
        libGridView.setAdapter(libAdapter);

        RelativeLayout.LayoutParams layoutParam = (android.widget.RelativeLayout.LayoutParams) editLayout.getLayoutParams();
        int marginLeft = (cusLableList.size()) % 4;
        layoutParam.setMargins(marginLeft * (GlobalData.screenWidth / 4), 0, 0, 0);
        RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) cusGridView.getLayoutParams();
        layoutHeight = layoutParams.height;

    }

    @ItemLongClick(R.id.lable_customer_grideview)
    void cusLongClick(int position) {
        cusLableList.get(position).setIsSelect(true);
        cusAdapter.notifyDataSetChanged();
    }

    @ItemClick(R.id.lable_grideview)
    void libItemClick(int position) {
        if (libLableList.get(position).isSelect()) {
            for (int i = 0; i < cusLableList.size(); i++) {
                if (cusLableList.get(i).getName().equals(libLableList.get(position).getName())) {
                    cusLableList.remove(i);
                }
            }
            libLableList.get(position).setIsSelect(false);
        } else {
            cusLableList.add(libLableList.get(position));
            libLableList.get(position).setIsSelect(true);
        }
        cusAdapter.notifyDataSetChanged();
        libAdapter.notifyDataSetChanged();
        modifyLayout();
    }

    public int layoutHeight;

    public void modifyLayout() {
        int lineNo = (cusLableList.size()) / 4 + 1;
        RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) cusGridView.getLayoutParams();
        layoutParams.height = layoutHeight * lineNo;
        cusGridView.setLayoutParams(layoutParams);
        RelativeLayout.LayoutParams layoutParam = (android.widget.RelativeLayout.LayoutParams) editLayout.getLayoutParams();
        int marginLeft = (cusLableList.size()) % 4;
        layoutParam.setMargins(marginLeft * (GlobalData.screenWidth / 4), 0, 0, 0);
    }


    XTHttp xtHttp = new XTHttp();
    String url = "";
    String param = "";

    private void getData() {
        param = "emp_id=" + GlobalData.counselor.getData().getEmployee_id();
        url = RequestAddr.lableLib + param;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
//                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    LableData lableData;

    private void dealData(Object o) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            lableData = mapper.readValue(o.toString(), LableData.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (lableData == null)
            return;


//        lableList =  customerDetail.getData().getLabels();
        for (int i = 0; i < lableData.getData().size(); i++) {
            libLableList.add(lableData.getData().get(i));

        }

        for (int i = 0; i < libLableList.size(); i++) {
            for (int j = 0; j < cusLableList.size(); j++) {
                if (libLableList.get(i).getName().equals(cusLableList.get(j).getName())) {
                    libLableList.get(i).setIsSelect(true);
                    break;
                }
            }
            MethedUtil.UtilLog("i:" + i + ",flag:" + libLableList.get(i).isSelect());
        }

        libAdapter.notifyDataSetChanged();


    }

    @Override
    @Click({R.id.back_btn, R.id.save_lable})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                MainActivity.getInstace().getSupportFragmentManager().popBackStack();
                break;
            case R.id.save_lable:
                saveTag();
                break;
        }
    }


    private void addTag(String name) {
        param = "emp_id=" + GlobalData.counselor.getData().getEmployee_id()+
        "&name="+name;
        url = RequestAddr.addlable + param;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealAddData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
//                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    PublicData publicData;

    private void dealAddData(Object o) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            publicData = mapper.readValue(o.toString(), PublicData.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (publicData == null)
            return;

        MethedUtil.UtilToast(getActivity(), publicData.getMsg());


    }

    private void saveTag() {
        String lableStr  = "";
        for (int i = 0; i < cusLableList.size(); i++) {
            if (i == cusLableList.size() -1){
                lableStr = lableStr + cusLableList.get(i).getName();
            }else{
                lableStr = lableStr + cusLableList.get(i).getName()+",";
            }


        }
        param = "customer_id=" + customer_id+
                "&name="+lableStr;
        url = RequestAddr.editLable + param;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealAddData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
//                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }


}
